package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.domain.vo.OrderForm;
import com.spzx.order.domain.vo.TradeVo;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.product.api.domain.vo.SkuStockVo;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.domain.UserAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    RabbitService rabbitService; //来自于公共模块：spzx-common-rabbit

    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo) {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    @Override
    public TradeVo orderTradeData() {
        Long userId = SecurityContextHolder.getUserId();

        // 获取购物车已选中商品
        R<List<CartInfo>> cartCheckedList = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);
        if (R.FAIL == cartCheckedList.getCode()) {
            throw new ServiceException(cartCheckedList.getMsg());
        }
        List<CartInfo> cartInfoList = cartCheckedList.getData();
        if (CollectionUtils.isEmpty(cartInfoList)) {
            throw new ServiceException("购物车无选中商品");
        }

        // 获取orderItemList
        List<OrderItem> orderItemList = null;
        BigDecimal totalAmount = new BigDecimal(0);
        orderItemList = cartInfoList.stream().map(cartInfo -> {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo, orderItem);
            return orderItem;
        }).toList();

        // 计算总金额
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }

        String tradeNo = generateTradeNo(userId);

        TradeVo tradeVo = new TradeVo();
        tradeVo.setTradeNo(tradeNo);
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);

        return tradeVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long submitOrder(OrderForm orderForm) {

        Long userId = SecurityContextHolder.getUserId();
        // 1.查重
        String tradeNo = orderForm.getTradeNo();
        String userTradeKey = "user:tradeNo" + userId;
        String script = """
               if redis.call("get",KEYS[1]) == ARGV[1] 
                    then return redis.call("del",KEYS[1])
                    else return 0
                    end
                """;
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script,Long.class);
        Long flag = (Long) redisTemplate.execute(redisScript, List.of(userTradeKey), tradeNo);
        if (flag==0) {
            throw new ServiceException("请勿重复提交订单");
        }

        // 2.form 不能为空

        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if (CollectionUtils.isEmpty(orderItemList)) {
            throw new ServiceException("数据不能为空");
        }

        // 3. 查看价格是否更新

        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).toList();
        R<List<SkuPrice>> skuPriceListR = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (R.FAIL == skuPriceListR.getCode()) {
            throw new ServiceException(skuPriceListR.getMsg());
        }
        List<SkuPrice> skuPriceListRData = skuPriceListR.getData();
        Map<Long, BigDecimal> skuIdToSalePriceMap = skuPriceListRData.stream()
                .collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));
        StringBuilder builderResult = new StringBuilder();
        for (OrderItem orderItem : orderItemList) {
            if (orderItem.getSkuPrice().compareTo(skuIdToSalePriceMap.get(orderItem.getSkuId()))!=0) {
                builderResult = builderResult.append(orderItem.getSkuNum() + "价格变化了;");
            }
        }
        if (StringUtils.hasText(builderResult.toString())) {
            //更新购物车价格
            remoteCartService.updateCartPrice(userId, SecurityConstants.INNER);
            throw new ServiceException(builderResult.toString());
        }


        // 4. 锁定库存
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(orderItem->{
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            return skuLockVo;
        }).toList();
        R<String> stringR = remoteProductService.checkAndLock(tradeNo, skuLockVoList, SecurityConstants.INNER);
        if (R.FAIL == stringR.getCode()) {
            throw new ServiceException(stringR.getMsg());
        }
        if (StringUtils.hasText(stringR.getData())) {
            throw new ServiceException(stringR.getData());
        }

        // 5. 下单
        Long orderId = null;
        try {
            //4 下单
            orderId = this.saveOrder(userId,orderForm);
        } catch (Exception e) {
            e.printStackTrace();
            //抛出异常
            throw new ServiceException("下单失败");
        }

        // 6. 删除
        remoteCartService.deleteCartCheckedList(userId, SecurityConstants.INNER);

        // 7. 发送延迟消息，订单延迟支付时间

        rabbitService.sendDealyMessage(MqConst.EXCHANGE_CANCEL_ORDER,
                MqConst.ROUTING_CANCEL_ORDER,
                String.valueOf(orderId),MqConst.CANCEL_ORDER_DELAY_TIME);

        return orderId;
    }

    @Override
    public void processCloseOrder(long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (orderInfo!=null && orderInfo.getOrderStatus()==0) {
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("未支付超时");
            orderInfoMapper.updateById(orderInfo);

            OrderLog orderLog = new OrderLog();
            orderLog.setNote("系统取消订单");
            orderLog.setProcessStatus(-1);
            orderLog.setOrderId(orderId);
            orderLog.setOperateUser("系统");
            orderLog.setRemark("超时");
            orderLogMapper.insert(orderLog);

            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT,MqConst.ROUTING_UNLOCK,orderInfo.getOrderNo());
        }
    }

    private Long saveOrder(Long userId, OrderForm orderForm) {

        String userName = SecurityContextHolder.getUserName();
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo(orderForm.getTradeNo());
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());

        R<UserAddress> userAddressR = remoteUserAddressService.getUserAddress(userId, SecurityConstants.INNER);
        if (R.FAIL == userAddressR.getCode()) {
            throw new ServiceException(userAddressR.getMsg());
        }
        UserAddress userAddress = userAddressR.getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount); // 没有 优惠卷 和 运费
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(orderForm.getFeightFee());
        //OrderInfo类的orderStatus属性的类型改为Integer
        orderInfo.setOrderStatus(0);
        orderInfoMapper.insert(orderInfo);


        //保存订单明细
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);
        }

        //记录日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLog.setOperateUser("用户");
        orderLogMapper.insert(orderLog);
        return orderInfo.getId();

    }

    private String generateTradeNo(Long userId) {
        String userTradeKey = "user:tradeNo" + userId;
        String uuid = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(userTradeKey,uuid,5, TimeUnit.MINUTES);
        return uuid;
    }

}